<?php

class cpl_category extends Model{
	public static function getTableName(){
		return 'cpl_category';
	}

	public function getParent()
	{
		$sql = 'select * from '.self::getTableName().' where parent_id=0';
		return Model::$dbo['r']->findBySql(__class__,$sql);
	}

	public function getSub($parentid, &$json_data)
	{
		$sql = 'select * from '.self::getTableName().' where parent_id='.$parentid;
		$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		if (count($ret) == 0)
		{
			$json_data['child'] = array();
			return ;
		}
		else
		{
			$j=0;
			foreach ($ret as $sub)
			{
				$child_data[$j] = array("id"=>$sub->id, "name"=>$sub->system_label);
				$this->getSub($sub->id,$child_data[$j]);
				$j++;
			}
			$json_data['child'] = $child_data;
		}
	}

	public function getSubCategorys($id = 0)
	{
		empty($id)	&&	$id	=	0;
		$sql = 'select * from '.self::getTableName().' where parent_id='.$id;
		$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		$res =	Model::object2array($ret);

		$tmp =	array();
		if (empty($id))
		{
			$tmp[0]	=	'Please Select...';
		}

		if (is_array($res))
		{
			foreach ($res	as	$subCategory)
			{
				$tmp[$subCategory['id']]=	$subCategory['system_label'];
			}
		}
		return	$tmp;
	}

	public function getCategoryByID($id)
	{
		$sql = 'select * from '.self::getTableName().' a
			left join `cpl_category-language` b on a.id=b.cpl_category_id 
			where b.cpl_category_id='.$id;
		$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		return	$ret;
	}

	/**
	 * get cpl category id by code
	 *
	 * @param string $parent_code : programme parent code from MAM
	 * @param string $sub_code    : programme category code from MAM
	 *
	 * @used by :  services/get_cpl_info.php
	 */
	public static function getCplCategoryID($parent_code, $sub_code)
	{
		$sql = 'select t1.system_label,t2.system_label,t2.id from '.self::getTableName().' t1 left join cpl_category t2 on t2.parent_id=t1.id where t1.code=\''.$parent_code.'\' and t2.code=\''.$sub_code.'\'';
		$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		return isset($ret[0]) ? $ret[0]->id : array();

	}

	/**
	 * check node if parent
	 *
	 * @param int $category_id : category id
	 *
	 * @used by : action/ProgrammeGetAction.class.php
	 */
	public function IsParent($category_id)
	{
		$sql = 'select parent_id from '.self::getTableName().' where id='.$category_id;
		$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		return ($ret[0]->parent_id == 0) ? true : false;
	}

	/**
	 * get tvbcom category id by cpl category id
	 *
	 * @param int $cpl_category_id : cpl category id
	 *
	 * @used by : action/ProgrammeAddAction.class.php
	 */
	public static function getTvbcomCategory($cpl_category_id)
	{
		$sql = 'select tvbcom_category_id from '.self::getTableName().' where id='.$cpl_category_id;
		$ret =  Model::$dbo['r']->findBySql(__class__,$sql);
		return ($ret[0]->tvbcom_category_id == 0) ? false : $ret[0]->tvbcom_category_id;
	}
}
?>
